<script setup>
import { ref, watch } from 'vue';
import { VDataTableServer } from 'vuetify/labs/VDataTable';
import AppCardCode from '@/views/liteflow/logic/AppCardCode.vue';
const props = defineProps({
  taskRow: Object,
})

const taskRow = ref(props.taskRow || {})

const getCurrentDate = () => {
  const today = new Date()
  const year = today.getFullYear()
  let month = today.getMonth() + 1
  let day = today.getDate()

  // 如果月份或日期是个位数，前面补零
  month = month < 10 ? '0' + month : month
  day = day < 10 ? '0' + day : day

  return `${year}-${month}-${day}`
}

// 表头
const headers = [
  {
    title: '执行器ID',
    key: 'jobGroup',
  },
  {
    title: '任务ID',
    key: 'jobId',
  },
  {
    title: '调度时间',
    key: 'triggerTime',
  },
  {
    title: '调度结果',
    key: 'triggerCode',
  },
  {
    title: '调度日志',
    key: 'triggerMsg',
  },
  {
    title: '执行时间',
    key: 'handleTime',
  },
  {
    title: '执行结果',
    key: 'handleCode',
  },
  {
    title: '执行日志',
    key: 'handleMsg',
  },
  {
    title: '操作',
    key: 'actions',
    sortable: false,
  },
]

const pageUrl = ref(API_URLS.xxljobLogPage)
const deleteUrl = ref(API_URLS.xxljobLogDelete)
const addUrl = ref(API_URLS.xxljobLogAdd)
const updateUrl = ref(API_URLS.xxljobLogUpdate)

const jobGroup = ref(taskRow.value.jobGroup || null)
const jobId = ref(taskRow.value.id || null)
const logStatus = ref()
const filterTime = ref(getCurrentDate())

onMounted(() => {
  jobGroupOptionSelect()
  if(jobGroup.value){
    jobInfoOptionSelect()
  }
})

const jobGroupOption = reactive([])

const jobGroupOptionSelect = async () => {
  const res = await $ivyApi.post(API_URLS.xxljobGroupOptions,{})
  jobGroupOption.push(...res.data)
}

const jobInfoOption = reactive([])

const jobInfoOptionSelect = async () => {
  jobInfoOption.length = 0
  const res = await $ivyApi.post(API_URLS.xxljobTaskOptions,{ jobGroup: jobGroup.value })
  jobInfoOption.push(...res.data)
}

watch(jobGroup, val => {
  if(val){
    jobInfoOptionSelect()
  }else{
    jobInfoOption.length = 0
  }
})

// 清理日志
const clearVisible = ref(false)

const clearOper = () => {
  clearVisible.value = true
}

const clearClick = async () => {
  clearVisible.value = false
  const res = await $ivyApi.post(API_URLS.xxljobLogClear,{
    jobId: jobId.value,
    jobGroup: jobGroup.value,
    logStatus: logStatus.value,
    filterTime: filterTime.value,
  })
  refreshPage(res)
}

// 分页列表
const totalPage = ref(1)
const totalRows = ref(0)
const list = ref([])
const loadings = ref(false)

// 分页参数
const options = ref({
  page: 1,
  itemsPerPage: 10,
  sortBy: [],
  groupBy: [],
  search: undefined,
})

const fetchList = async (msg) => {
  loadings.value = true
  const res = await $ivyApi.post(pageUrl.value,{
    jobId: jobId.value,
    jobGroup: jobGroup.value,
    logStatus: logStatus.value,
    filterTime: filterTime.value,
    options: options.value,
  })

  const data = res.data
  list.value = data.list
  totalPage.value = data.totalPage
  totalRows.value = data.totalRow
  options.value.page = data.page
  loadings.value = false

  if(typeof msg === 'string'){
    res.message = msg
    showMsg(res)
  }
}

watchEffect(fetchList)
// 监听 options 对象的变化，并在变化时调用 fetchList 方法
watch(options, async () => { await fetchList() }, { deep: true })

// 新增&编辑操作
const currRow = ref({})

const addOper = () => {
  currRow.value = {}
  editVisible.value = true
}

const updateOper = row => {
  currRow.value = row
  editVisible.value = true
}

const editVisible = ref(false)
const editRef = ref(null)

const editCallMethod = () => {
  editVisible.value = false
  editRef.value.saveItem()
}

const editCancelMethod = () =>{
  editVisible.value = false
}

const refreshPage = res => {
  showMsg(res)
  fetchList()
}

// 查看
const viewOper = row => {
  currRow.value = row
}


// 删除
const deleteId = ref('')
const deleteVisible = ref(false)

const deleteOper = id => {
  deleteVisible.value = true
  deleteId.value = id
}

// 确认删除
const deleteAgreeCmp = async (id) => {
  const res = await $ivyApi.post(deleteUrl.value,{
    id: deleteId.value,
  })

  showMsg(res)
  fetchList()
  deleteVisible.value = false
  deleteId.value = ''
}

// 终止任务
const killId = ref('')
const killVisible = ref(false)

const killOper = id => {
  killVisible.value = true
  killId.value = id
}

// 确认终止任务
const killAgreeCmp = async (id) => {
  const res = await $ivyApi.post(API_URLS.xxljobLogKill,{
    id: killId.value,
  })
  killVisible.value = false
  killId.value = ''
  refreshPage(res)
}

// 查看日志详情
const logDetailCatVisible = ref(false)
const fromLineNum = ref(1)
const logContent = ref('')

const logDetailCatOper = async (row) => {

  const res = await $ivyApi.post(API_URLS.xxljobLogLogDetailCat,{
    id: row.id,
    fromLineNum: fromLineNum.value,
  })

  const data = res.data
  if (res.code == 200) {



    if (!data) {
      console.log('pullLog fail')

      return
    }
    if (fromLineNum.value != data.fromLineNum) {
      console.log('pullLog fromLineNum not match')

      return
    }
    if (fromLineNum.value > data.toLineNum ) {
      console.log('pullLog already line-end')

      if (data.end) {

        return
      }

      return
    }

    logContent.value = { 'js': data.logContent }
    logDetailCatVisible.value = true
  } else {
    console.log('pullLog fail:'+res.message)
  }

}

// 回调信息
const snackbar = reactive(API_URLS.resultMsg)

const showMsg = res => {
  $resultMsg.show(res,snackbar)
}

//
const triggerCodeOption = [
  { color: 'error', title: '失败', value: 500 },
  { color: 'success', title: '成功', value: 200 },
  { color: 'primary', title: '', value: 0 },
]

const resolveTriggerCodeVariant = status => {
  return triggerCodeOption.filter(obj => obj.value == status)[0]
}

const handlerCodeOption = [
  { color: 'error', title: '失败', value: 500 },
  { color: 'info', title: '超时', value: 502 },
  { color: 'success', title: '成功', value: 200 },
  { color: 'primary', title: '', value: 0 },
]

const resolveHandlerCodeVariant = status => {
  return handlerCodeOption.filter(obj => obj.value == status)[0]
}

const logStatusOption = [
  { title: '成功', value: 1 },
  { title: '失败', value: 2 },
  { title: '进行中', value: 3 },
]
</script>

<template>
  <section>
    <VRow>
      <VSnackbar
        v-model="snackbar.msgVisible"
        location="top"
        :color="snackbar.msgColor"
      >
        {{ snackbar.msgContent }}
      </VSnackbar>

      <VCol cols="12">
        <VCard title="">
          <VCardText>
            <VRow>
              <VCol cols="3">
                <VSelect
                  v-model="jobGroup"
                  label="任务执行器"
                  :items="jobGroupOption"
                  clearable
                  item-title="title"
                  item-value="id"
                />
              </VCol>
              <VCol cols="3">
                <VSelect
                  v-model="jobId"
                  label="任务"
                  :items="jobInfoOption"
                  clearable
                  item-title="jobDesc"
                  item-value="id"
                />
              </VCol>
              <VCol cols="3">
                <VSelect
                  v-model="logStatus"
                  :items="logStatusOption"
                  label="状态"
                  clearable
                />
              </VCol>
              <VCol cols="3">
                <AppDateTimePicker
                  v-model="filterTime"
                  variant="outlined"
                  placeholder="调度时间"
                  clearable
                  :config="{ mode: 'range' }"
                />
              </VCol>
            </VRow>
          </VCardText>

          <VDivider />

          <VCardText class="d-flex flex-wrap py-4 gap-4">
            <div class="me-3 d-flex gap-3">
              <AppSelect
                :model-value="options.itemsPerPage"
                :items="[
                  { value: 10, title: '10' },
                  { value: 20, title: '20' },
                  { value: 50, title: '50' },
                  { value: 100, title: '100' },
                ]"
                style="inline-size: 6.25rem;"
                @update:model-value="options.itemsPerPage = parseInt($event, 10)"
              />
            </div>
            <VSpacer />

            <div class="d-flex align-center flex-wrap gap-4">
              <VBtn
                :loading="loadings"
                :disabled="loadings"
                size="38"
                @click="fetchList('刷新成功')"
              >
                <VIcon
                  icon="tabler-refresh"
                  size="22"
                />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  刷新
                </VTooltip>
              </VBtn>
              <VBtn
                prepend-icon="tabler-trash"
                color="error"
                @click="clearOper"
              >
                清理日志
              </VBtn>
            </div>
          </VCardText>

          <VDivider />

          <VDataTableServer
            v-model:items-per-page="options.itemsPerPage"
            v-model:page="options.page"
            :items="list"
            :items-length="totalRows"
            :headers="headers"
            class="text-no-wrap"
            @update:options="options = $event"
          >
            <template #item.jobGroup="{ item }">
              <span class="font-weight-medium">
                <VBtn
                  variant="plain"
                  size="small"
                  style="padding-inline-start: 0;"
                >
                  {{ item.jobGroup }}
                  <VTooltip
                    activator="parent"
                    location="top"
                  >
                    <span>执行器名称 ：{{ item.xxlJobGroup.title }}<br></span>
                    <span>执行器地址 ：{{ item.executorAddress }}<br></span>
                  </VTooltip>
                </VBtn>
              </span>
            </template>

            <template #item.jobId="{ item }">
              <span class="font-weight-medium">
                <VBtn
                  variant="plain"
                  size="small"
                  style="padding-inline-start: 0;"
                >
                  {{ item.jobId }}
                  <VTooltip
                    activator="parent"
                    location="top"
                  >
                    <span>任务名称：{{ item.xxlJobInfo.jobDesc }}<br></span>
                    <span>任务类&nbsp;&nbsp;&nbsp;&nbsp;：{{ item.executorHandler }}<br></span>
                    <span>任务参数：{{ item.executorParam }}<br></span>
                  </VTooltip>
                </VBtn>
              </span>
            </template>

            <template #item.triggerTime="{ item }">
              <span class="font-weight-medium">{{ item.triggerTime }}</span>
            </template>

            <template #item.triggerCode="{ item }">
              <VChip
                :color="resolveTriggerCodeVariant(item.triggerCode).color"
                class="font-weight-medium"
                size="small"
              >
                {{ resolveTriggerCodeVariant(item.triggerCode).title }}
              </VChip>
            </template>

            <template #item.triggerMsg="{ item }">
              <span class="font-weight-medium">
                <VBtn
                  variant="plain"
                  size="small"
                  style="padding-inline-start: 0;"
                >
                  查看
                  <VTooltip
                    activator="parent"
                    location="top"
                  >
                    <span v-html="item.triggerMsg" />
                  </VTooltip>
                </VBtn>
              </span>
            </template>

            <template #item.handleTime="{ item }">
              <span class="font-weight-medium">{{ item.handleTime }}</span>
            </template>

            <template #item.handleCode="{ item }">
              <VChip
                v-if="resolveHandlerCodeVariant(item.handleCode).title != ''"
                :color="resolveHandlerCodeVariant(item.handleCode).color"
                class="font-weight-medium"
                size="small"
              >
                {{ resolveHandlerCodeVariant(item.handleCode).title }}
              </VChip>
            </template>

            <template #item.handleMsg="{ item }">
              <span class="font-weight-medium">
                <VBtn
                  variant="plain"
                  size="small"
                  style="padding-inline-start: 0;"
                >
                  查看
                  <VTooltip
                    activator="parent"
                    location="top"
                  >
                    <span v-html="item.handleMsg" />
                  </VTooltip>
                </VBtn>
              </span>
            </template>

            <template #item.actions="{ item }">
              <IconBtn
                v-if="item.triggerCode == 200 || item.handleCode != 0"
                @click="logDetailCatOper(item)"
              >
                <VIcon icon="tabler-file" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  执行日志
                </VTooltip>
              </IconBtn>

              <IconBtn
                v-if="(item.triggerCode == 200 || item.handleCode != 0) && item.handleCode == 0"
                @click="killOper(item.id)"
              >
                <VIcon icon="tabler-clock-pause" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  终止任务
                </VTooltip>
              </IconBtn>
            </template>


            <!-- pagination -->
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-sm-space-between justify-center flex-wrap gap-3 pa-5 pt-3">
                <p class="text-sm text-disabled mb-0">
                  共<span style="color: #7367f0;">&nbsp;{{ totalRows }}&nbsp;</span>条记录
                </p>
                <VPagination
                  v-model="options.page"
                  :length="Math.ceil(totalRows / options.itemsPerPage)"
                  :total-visible="$vuetify.display.xs ? 1 : Math.ceil(totalRows / options.itemsPerPage)"
                >
                  <template #prev="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      上一页
                    </VBtn>
                  </template>

                  <template #next="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      下一页
                    </VBtn>
                  </template>
                </VPagination>
              </div>
            </template>
          </VDataTableServer>
          <!-- SECTION -->
        </VCard>

        <VDialog
          v-model="clearVisible"
          max-width="600"
          persistent
        >
          <DialogCloseBtn @click="clearVisible = !clearVisible" />
          <VCard title="清理日志">
            <VCardText>
              <VRow>
                <VCol cols="12">
                  <VSelect
                    v-model="jobGroup"
                    label="任务执行器"
                    :items="jobGroupOption"
                    clearable
                    item-title="title"
                    item-value="id"
                  />
                </VCol>
                <VCol cols="12">
                  <VSelect
                    v-model="jobId"
                    label="任务"
                    :items="jobInfoOption"
                    clearable
                    item-title="jobDesc"
                    item-value="id"
                  />
                </VCol>
                <VCol cols="12">
                  <AppDateTimePicker
                    v-model="filterTime"
                    variant="outlined"
                    placeholder="调度时间"
                    clearable
                    :config="{ mode: 'range' }"
                  />
                </VCol>
                <VCol cols="12">
                  <VSelect
                    v-model="logStatus"
                    :items="logStatusOption"
                    label="状态"
                    clearable
                  />
                </VCol>
              </VRow>
            </VCardText>
            <VCardText class="d-flex justify-end flex-wrap gap-3">
              <VBtn
                variant="tonal"
                color="secondary"
                @click="clearVisible = false"
              >
                关闭
              </VBtn>
              <VBtn @click="clearClick">
                清理
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>

        <!-- 删除确认 -->
        <VDialog
          v-model="deleteVisible"
          width="300"
        >
          <DialogCloseBtn @click="deleteVisible = !deleteVisible" />
          <VCard title="提示">
            <VCardText> 是否确认删除？ </VCardText>
            <VCardText class="d-flex justify-end gap-3 flex-wrap">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="deleteVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="deleteAgreeCmp">
                确定
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>

        <!-- 终止确认 -->
        <VDialog
          v-model="killVisible"
          width="300"
        >
          <DialogCloseBtn @click="killVisible = !killVisible" />
          <VCard title="提示">
            <VCardText> 是否确认终止任务？ </VCardText>
            <VCardText class="d-flex justify-end gap-3 flex-wrap">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="killVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="killAgreeCmp">
                确定
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>

        <!-- 日志详情 -->
        <VDialog
          v-model="logDetailCatVisible"
          class="v-dialog-sm"
          max-width="80%"
          min-width="80%"
        >
          <DialogCloseBtn @click="logDetailCatVisible = !logDetailCatVisible" />

          <VCard title="日志详情">
            <VCardText>
              <AppCardCode
                title=""
                code-language="js"
                :code="logContent"

                show-code
                :show-title="false"
                class="el-code"
              />
            </VCardText>

            <VCardText class="d-flex justify-end flex-wrap gap-3">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="logDetailCatVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="logDetailCatVisible = false">
                确认
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>
      </vcol>
    </vrow>
  </section>
</template>

<style lang="scss">
.text-capitalize {
  text-transform: capitalize;
}

.user-list-name:not(:hover) {
  color: rgba(var(--v-theme-on-background), var(--v-medium-emphasis-opacity));
}
</style>
